package com.zy.pro.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.zy.utils.GsonHelper;

/*** 
 * java抓取网络图片 
 * @author jiangyingxu 
 * 
 */  
public class CatchImage {  
  
    // 地址  
    private static final String URL = "http://www.csdn.net";  
    // 编码  
    private static final String ECODING = "UTF-8";  
    // 获取img标签正则  
    private static final String IMGURL_REG = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";  
    // 获取src路径的正则  
    private static final String IMGSRC_REG = "http:\"?(.*?)(\"|>|\\s+)";  
  
      
    public static void main(String[] args) throws Exception {  
        CatchImage cm = new CatchImage();  
        //获得html文本内容  
        String HTML = cm.getHTML(URL);  
        //获取图片标签  
        HTML = "<html><head><body><div class=\"\" style=\"left: 0px; top: 0px; visibility: hidden; position: absolute;\"><div align=\"center\"><form id=\"newsForm\" enctype=\"multipart/form-data\" action=\"http://localhost:8088/mycell/control/news/newsController/edit.do\" method=\"post\"><input id=\"newsId\" type=\"hidden\" value=\"2\" name=\"newsId\"><table width=\"90%\" cellspacing=\"1\" cellpadding=\"3\" border=\"0\"><tbody><tr height=\"2px\"><tr height=\"35px;\" bgcolor=\"#f5f5f5\"><tr height=\"20px\"><tr height=\"35px;\"><tr height=\"35px;\"><tr height=\"35px;\"><tr height=\"35px;\"><td width=\"25%\" align=\"right\"><td width=\"75%\"><div class=\"ke-container ke-container-default\" style=\"width: 700px;\"><div class=\"ke-toolbar\" style=\"display:block;\" unselectable=\"on\"><div class=\"ke-edit\" style=\"display: block; height: 163px;\"><iframe class=\"ke-edit-iframe\" frameborder=\"0\" hidefocus=\"true\" style=\"width: 100%; height: 163px;\" tabindex=\"\"><html><head><body class=\"ke-content\"><div align=\"right\">致小区各位业主：<br>随着各类工业、工厂的兴起，我们饮用的矿泉水质量不达标，为了小区内各位业主有个健康的身体，经我司业务经理在市场多天的考察与净水器公司达成合作关系， 原170元/台的净水器，合作关系价格140元/台，费用全由公司支付（业主不用支付净水器的费用，但要支付。。。。。。。，用来。。。。）<br>一、活动时间<br>2014-04-18日 09：00分------2014-4月20日17：30分<br>二、活动地点<img alt=\"\" data-ke-src=\"/mycell/upload/6/news/2014/06/01/16/545c098e-31a7-4956-a6b9-ccd7dec19383.gif\" src=\"/mycell/upload/6/news/2014/06/01/16/545c098e-31a7-4956-a6b9-ccd7dec19383.gif\"><br>业务部一楼大厅<br>三、活动要求<img alt=\"\" data-ke-src=\"/mycell/upload/6/news/2014/06/01/16/545c098e-31a7-4956-a6b9-ccd7dec19383.gif\" src=\"/mycell/upload/6/news/2014/06/01/16/545c098e-31a7-4956-a6b9-ccd7dec1938332.gif\"><br>必须是小区内的业主，请携带好本人身份证，免费领取1台净水器<br><div align=\"center\"></body></html></iframe><textarea class=\"ke-edit-textarea\" hidefocus=\"true\" style=\"width: 100%; height: 161px; display: none;\" tabindex=\"\"></textarea></div><div class=\"ke-statusbar\"></div><textarea id=\"content\" style=\"width: 700px; height: 200px; display: none;\" rows=\"8\" cols=\"100\" name=\"content\"><div align=\"right\"> 关于物业小区免费送净水器的活动通知<br /> </div> 致小区各位业主：<br /> 随着各类工业、工厂的兴起，我们饮用的矿泉水质量不达标，为了小区内各位业主有个健康的身体，经我司业务经理在市场多天的考察与净水器公司达成合作关系， 原170元/台的净水器，合作关系价格140元/台，费用全由公司支付（业主不用支付净水器的费用，但要支付。。。。。。。，用来。。。。）<br /> 一、活动时间<br /> 2014-04-18日 09：00分------2014-4月20日17：30分<br /> 二、活动地点<img src=\"/mycell/upload/6/news/2014/06/01/16/545c098e-31a7-4956-a6b9-ccd7dec19383.gif\" alt=\"\" /><br /> 业务部一楼大厅<br /> 三、活动要求<br /> 必须是小区内的业主，请携带好本人身份证，免费领取1台净水器<br /> <div align=\"center\"> 小区业务部<br /> 2014-04-18日<br /> </div></textarea></td></tr><tr height=\"35px;\"><tr height=\"40px;\"></tbody></table></form></div><object id=\"b5tplugin\" width=\"0\" height=\"0\" type=\"application/x-bang5taoplugin\" style=\"position:absolute;left:-9000px;top:-9000px;\"></object><div class=\"panel combo-p\" style=\"position: absolute; z-index: 10; display: none; width: 95px;\"></body></html>";
        List<String> imgUrl = cm.getImageUrl(HTML);  
        System.out.println(GsonHelper.toJson(imgUrl));
        
        
        //获取图片src地址  
        List<String> imgSrc = cm.getImageSrc(HTML);  
        System.out.println(GsonHelper.toJson(imgSrc));
        
        
        //下载图片  
        cm.Download(imgSrc);  
    }  
      
      
    /*** 
     * 获取HTML内容 
     *  
     * @param url 
     * @return 
     * @throws Exception 
     */  
    public static String getHTML(String url) throws Exception {  
        URL uri = new URL(url);  
        URLConnection connection = uri.openConnection();  
        InputStream in = connection.getInputStream();  
        byte[] buf = new byte[1024];  
        int length = 0;  
        StringBuffer sb = new StringBuffer();  
        while ((length = in.read(buf, 0, buf.length)) > 0) {  
            sb.append(new String(buf, ECODING));  
        }  
        in.close();  
        return sb.toString();  
    }  
  
    /*** 
     * 获取ImageUrl地址 
     *  
     * @param HTML 
     * @return 
     */  
    public static List<String> getImageUrl(String HTML) {  
        Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);  
        List<String> listImgUrl = new ArrayList<String>();  
        while (matcher.find()) {  
            listImgUrl.add(matcher.group());  
        }  
        return listImgUrl;  
    }  
    
    /*** 
     * 获取ImageSrc地址 
     *  
     * @param listImageUrl 
     * @return 
     */  
    public static List<String> getImageSrc(String HTML) {  
    	 Matcher matcher = Pattern.compile(IMGURL_REG).matcher(HTML);  
         List<String> listImgSrc = new ArrayList<String>();  
         while (matcher.find()) {  
        	 listImgSrc.add(matcher.group(1));  
         }  
         return listImgSrc;  
    }  
  
    /*** 
     * 获取ImageSrc地址 
     *  
     * @param listImageUrl 
     * @return 
     */  
    public static List<String> getImageSrc(List<String> listImageUrl) {  
        List<String> listImgSrc = new ArrayList<String>();  
        for (String image : listImageUrl) {  
            Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(image);  
            while (matcher.find()) {  
                listImgSrc.add(matcher.group().substring(0, matcher.group().length() - 1));  
            }  
        }  
        return listImgSrc;  
    }  
  
    /*** 
     * 下载图片 
     *  
     * @param listImgSrc 
     */  
    public static void Download(List<String> listImgSrc) {  
        try {  
            for (String url : listImgSrc) {  
                String imageName = url.substring(url.lastIndexOf("/") + 1, url.length());  
                URL uri = new URL(url);  
                InputStream in = uri.openStream();  
                FileOutputStream fo = new FileOutputStream(new File(imageName));  
                byte[] buf = new byte[1024];  
                int length = 0;  
                System.out.println("开始下载:" + url);  
                while ((length = in.read(buf, 0, buf.length)) != -1) {  
                    fo.write(buf, 0, length);  
                }  
                in.close();  
                fo.close();  
                System.out.println(imageName + "下载完成");  
            }  
        } catch (Exception e) {  
            System.out.println("下载失败");  
        }  
    }  
  
      
}  